/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：太平金科-基础组件封装层-SpringCloud组件封装-缺省实现
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taipingframework.cloud.web.autoconfigure;

import com.taipingframework.cloud.web.openfeign.DefaultClientWrapper;
import com.taipingframework.cloud.web.openfeign.FeignClientAdvice;
import com.taipingframework.cloud.web.openfeign.FeignClientRequestAdvice;
import com.taipingframework.cloud.web.openfeign.FeignClientResponseAdvice;
import com.taipingframework.cloud.web.properties.FeignHeaderProperty;
import feign.Client;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.loadbalancer.FeignLoadBalancerAutoConfiguration;
import org.springframework.cloud.openfeign.loadbalancer.OnRetryNotEnabledCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Client.class)
@AutoConfigureBefore(FeignLoadBalancerAutoConfiguration.class)
public class FeignClientAutoConfiguration {

    /**
     * Feign执行远程HTTP接口调用时 需要设置的 请求头入参列表 和 响应头出参列表
     */
    @Bean
    @ConfigurationProperties(prefix = "application.feign")
    public FeignHeaderProperty feignHeaderProperty() {
        return new FeignHeaderProperty();
    }

    /**
     * FeignClient执行HTTP请求时的前置通知
     */
    @Bean
    public FeignClientRequestAdvice feignClientRequestAdvice(FeignClientAdvice feignClientAdvice) {
        return new FeignClientRequestAdvice(feignClientAdvice);
    }

    /**
     * 实现OpenFeign发送HTTP请求的返回通知
     */
    @Bean
    public FeignClientResponseAdvice feignClientResponseAdvice(FeignClientAdvice feignClientAdvice) {
        return new FeignClientResponseAdvice(feignClientAdvice);
    }

    /**
     * 自定义Feign的Client
     * 具体请参考源码 {@link org.springframework.cloud.openfeign.loadbalancer.DefaultFeignLoadBalancerConfiguration}
     */
    @Bean
    @Conditional({OnRetryNotEnabledCondition.class})
    public Client feignClient(BlockingLoadBalancerClient loadBalancerClient,
                              FeignClientResponseAdvice feignClientResponseAdvice) {
        DefaultClientWrapper clientWrapper = new DefaultClientWrapper((SSLSocketFactory) null, (HostnameVerifier) null, feignClientResponseAdvice);
        return new FeignBlockingLoadBalancerClient(clientWrapper, loadBalancerClient);
    }

}
